<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import userApi from '../api/userApi';
import useNavToHome from '@/hooks/useNavToHome'
import usePageTitle from '@/hooks/usePageTitle'

usePageTitle('登录')
useNavToHome()

const router = useRouter();

const formRef = ref()
const loginForm = reactive({
    username: '',
    password: '',
});

const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { pattern: /^[A-Za-z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 10, message: '密码长度在5到10个字符之间', trigger: 'blur' },
    ],
};

function handleLogin(formRef) {
    // 表单验证
    formRef.validate(async (valid) => {
        if (!valid) {
            console.log('表单校验失败');
            return false;
        }

        // 执行登录逻辑
        const { token } = await userApi.login(loginForm);
        // 存储token
        localStorage.setItem('token', token);
        router.push('/');
    });
}
</script>

<template>
    <div class="login">
        <div class="login-container">
            <h2 class="login-title">用户登录</h2>
            <el-form :model="loginForm" :rules="rules" ref="formRef" label-position="top" class="login-form">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="loginForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="loginForm.password"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleLogin(formRef)">登录</el-button>
                    &nbsp;&nbsp;
                    <router-link to="/register">没有账号？去注册</router-link>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<style scoped>
.login {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 80vh;
}

.login-container {
    width: 400px;
    padding: 20px;
    background-color: #f6f6f6;
    border-radius: 4px;
}

.login-title {
    text-align: center;
    margin-bottom: 20px;
}

.login-form {
    margin-top: 20px;
}
</style>
